import {ref, toRefs, toRaw, watch} from 'vue'
import type VChart from 'vue-echarts'
import {customizeHttp} from '@/api/http'
import {useChartDataPondFetch, ws} from '@/hooks/'
import {CreateComponentType, ChartFrameEnum} from '@/packages/index.d'
import {useChartEditStore} from '@/store/modules/chartEditStore/chartEditStore'
import {RequestDataTypeEnum} from '@/enums/httpEnum'
import {isPreview, newFunctionHandle, intervalUnitHandle, getLocalStorage} from '@/utils'
import {setOption} from '@/packages/public/chart'
import router from '@/router'

// 获取类型
type ChartEditStoreType = typeof useChartEditStore

let INTERVAL: any = {}

/**
 * useChartDataFetch 数据监听与更改
 * @param targetComponent
 * @param useChartEditStore 若直接引会报错，只能动态传递
 * @param updateCallback 自定义更新函数
 */
const useChartDataFetch = (
    targetComponent: CreateComponentType,
    useChartEditStore: ChartEditStoreType,
    updateCallback?: (...args: any) => any
) => {
    const vChartRef = ref<typeof VChart | null>(null)
    let fetchInterval: any = 0

    // 数据池
    const {addGlobalDataInterface} = useChartDataPondFetch()

    // 组件类型
    const {chartFrame} = targetComponent.chartConfig

    // eCharts 组件配合 vChart 库更新方式
    const echartsUpdateHandle = (dataset: any) => {
        if (chartFrame === ChartFrameEnum.ECHARTS) {
            if (vChartRef.value) {
                setOption(vChartRef.value, {dataset: dataset})
            }
        }
    }

    const requestIntervalFn = () => {
        const chartEditStore = useChartEditStore()

        // 全局数据
        const {
            requestOriginUrl,
            requestIntervalUnit: globalUnit,
            requestInterval: globalRequestInterval
        } = toRefs(chartEditStore.getRequestGlobalConfig)

        // 目标组件
        const {
            requestDataType,
            requestUrl,
            requestIntervalUnit: targetUnit,
            requestInterval: targetInterval,
            socketParamToString
        } = toRefs(targetComponent.request)

        // 非请求类型
        if (requestDataType.value === RequestDataTypeEnum.AJAX) {
            try {
                // 处理地址
                // @ts-ignore
                if (requestUrl?.value) {
                    // requestOriginUrl 允许为空
                    const completePath = requestOriginUrl && requestOriginUrl.value + requestUrl.value
                    if (!completePath) return

                    const fetchFn = async () => {
                        let type = targetComponent.chartConfig?.type === "chart" ? 1 : 2
                        const res = await customizeHttp(
                            toRaw(targetComponent.request),
                            toRaw(chartEditStore.getRequestGlobalConfig),
                            String(type)
                        )
                        if (res) {
                            try {
                                const filter = targetComponent.filter
                                const {data} = res
                                echartsUpdateHandle(newFunctionHandle(data, res, filter))
                                // 更新回调函数
                                if (updateCallback) {
                                    updateCallback(newFunctionHandle(data, res, filter))
                                }
                            } catch (error) {
                                console.error(error)
                            }
                        }
                    }

                    // 普通初始化与组件交互处理监听
                    watch(
                        () => targetComponent.request,
                        () => {
                            fetchFn()
                        },
                        {
                            immediate: true,
                            deep: true
                        }
                    )

                    // 定时时间
                    const time = targetInterval && targetInterval.value ? targetInterval.value : globalRequestInterval.value
                    // 单位
                    const unit = targetInterval && targetInterval.value ? targetUnit.value : globalUnit.value
                    // 开启轮询
                    if (time) {
                        fetchInterval = setInterval(fetchFn, intervalUnitHandle(time, unit))
                        INTERVAL[targetComponent.id] = fetchInterval
                    }
                }
                // console.log(INTERVAL, 2)
                // eslint-disable-next-line no-empty
            } catch (error) {
                console.log(error)
            }
        } else if (requestDataType.value === RequestDataTypeEnum.Socket) {
            // 如果是Socket配置的话
            // let sw = new UseWebsocket(socketUrl)
            // 声明订阅数据类型,除曲线外都是单个数据
            let type = targetComponent.chartConfig?.type === "chart" ? 1 : 2
            if (ws.value !== null) {
                // type: 0 ,1所有数据,2最后一个
                ws.value.send({
                    componentId: targetComponent.id,
                    data: socketParamToString.value,
                    type: type,
                    mid: getLocalStorage("CURRENT_TASK").mid
                })

                ws.value.on(targetComponent.id, res => {
                    const filter = targetComponent.filter
                    // 更新回调函数
                    let D = res.data.filter((s: any) => {
                        return s.componentId === targetComponent.id
                    })
                    if (updateCallback && D.length > 0) {
                        if (typeof D[0]['paramValueList'] !== 'undefined') {
                            updateCallback(newFunctionHandle(D[0].paramValueList, res, filter))
                        } else if (typeof D[0]['paramValue'] !== 'undefined') {
                            updateCallback(newFunctionHandle(D[0].paramValue, res, filter))
                        }
                    }
                })
            }

            // sw.connectionSocket()
            // sw.send({a: 1})
            // sw.on('kkk', (res) => {
            //   console.log(res)
            // })
        }
    }

    if (isPreview()) {
        // 如果是显示界面
        // 判断是否是数据池类型
        targetComponent.request.requestDataType === RequestDataTypeEnum.Pond
            ? addGlobalDataInterface(targetComponent, useChartEditStore, updateCallback || echartsUpdateHandle)
            : requestIntervalFn()
    }
    return {vChartRef}
}

/**
 * clearHttpRequest 清除HTTP轮询
 * @param id
 */
const clearHttpRequest = (id: string) => {
    clearInterval(INTERVAL[id])
    delete INTERVAL[id]
}

export {useChartDataFetch, clearHttpRequest}
